<template>
  <div class="login-container">
    <n-card title="用户登录" class="login-card">
      <n-form 
        ref="formRef" 
        :model="formData" 
        :rules="rules"
        @submit.prevent="handleSubmit"
      >
        <n-form-item path="username" label="用户名">
          <n-input
            v-model:value="formData.username"
            placeholder="请输入用户名"
            clearable
          />
        </n-form-item>

        <n-form-item path="password" label="密码">
          <n-input
            v-model:value="formData.password"
            type="password"
            placeholder="请输入密码"
            clearable
            show-password-on="click"
          />
        </n-form-item>

        <n-button 
          attr-type="submit"
          type="primary"
          block
          :loading="submitting"
        >
          登录
        </n-button>
      </n-form>
    </n-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { 
  NForm, 
  NFormItem, 
  NInput, 
  NButton, 
  NCard,
  useMessage 
} from 'naive-ui'
import { useRouter } from 'vue-router'
import { useAccount } from '../store/account'

const router = useRouter()
const formRef = ref(null)
const message = useMessage()
const submitting = ref(false)
const account = useAccount()

const formData = reactive({
  username: '',
  password: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, message: '密码长度不能小于3位', trigger: 'blur' }
  ]
}

const handleSubmit = async () => {
  try {
    // 表单验证
    submitting.value = true 
    formRef.value?.validate()
    
    // 发送登录请求
    let res = await account.userLogin(formData)

    if(res.data.code == 1) {
        router.push('/')
        return
    }
    if(res.data.code == 0) {
        if(res.data.msg == '用户名不存在') {
            formData.username = ''
        }
        formData.password = ''
        return
    }
  } catch (error) {
    message.error(error.message || '登录失败，请检查输入')
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.login-card {
  width: 400px;
  border-radius: 8px;
  box-shadow: 0 2px 12px #0000001a;
}
</style>